package com.freedom.admin.application.service.query;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freedom.admin.application.converter.RoleConverter;
import com.freedom.admin.domain.repository.MenuRepository;
import com.freedom.admin.domain.repository.RolePermissionRepository;
import com.freedom.admin.domain.repository.RoleRepository;
import com.freedom.admin.infrastructure.persistence.pojo.bo.RoleBO;
import com.freedom.admin.infrastructure.persistence.pojo.bo.RolePageBO;
import com.freedom.admin.infrastructure.persistence.pojo.form.RoleResourceForm;
import com.freedom.admin.infrastructure.persistence.pojo.query.RolePageQuery;
import com.freedom.admin.infrastructure.persistence.pojo.vo.role.RolePageVO;
import com.freedom.admin.infrastructure.persistence.pojo.vo.role.RoleVO;
import com.freedom.common.framework.pojo.OptionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RoleQueryService {

    private final RoleRepository roleRepository;

    private final MenuRepository menuRepository;

    private final RolePermissionRepository rolePermissionRepository;

    private final RoleConverter roleConverter;

    public Page<RolePageVO> listRolePages(RolePageQuery queryParams) {
        Page<RolePageBO> rolePage = roleRepository.listRolePages(queryParams);
        return roleConverter.toPageVO(rolePage);
    }

    public List<OptionVO> listRoleOptions() {
        List<RoleBO> roleList = roleRepository.queryRoleList();
        return roleList.stream().map(item -> new OptionVO(item.getId(), item.getName())).collect(Collectors.toList());
    }

    public RoleVO getRoleDetail(Integer roleId) {
        RoleBO roleBO = roleRepository.findById(roleId);
        RoleVO roleVO = roleConverter.toVO(roleBO);

        List<Integer> menuIds = menuRepository.findIdByRoleId(roleId);
        roleVO.setMenuIds(menuIds);

        List<Integer> permissionIds = rolePermissionRepository.findPermissionIdsByRoleId(roleId);
        roleVO.setPermissionIds(permissionIds);

        return roleVO;
    }

    public RoleResourceForm getRoleResources(Integer roleId) {
        RoleBO roleBO = roleRepository.findById(roleId);
        return roleConverter.toForm(roleBO);
    }
}
